// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { _decorator, Component, Prefab, Node, Label, instantiate, Vec3, director, AudioSource, Tween, log } from 'cc';
import Player from './Player';
import Star from './Star';
const { ccclass, property } = _decorator;

@ccclass('Game')
export default class Game extends Component {
    @property(Prefab)
    private starPrefab: Prefab = null!;
    @property
    private maxStarDuration: number = 0;
    @property
    private minStarDuration: number = 0;
    @property(Node)
    private ground: Node = null!;
    @property(Node)
    public player: Node = null!;
    groundY: number = 0;
    @property(Label)
    private scoreDisplay: Label = null!;
    private score: number = 0;
    public timer: number = 0;
    public starDuration: number = 0;
    public _starPos: Vec3 = new Vec3();

    @property(AudioSource)
    scoreAudioSource: AudioSource = null!;

    // LIFE-CYCLE CALLBACKS:    
    spawnNewStar() {
        let newStar = instantiate(this.starPrefab);
        this.node.addChild(newStar);
        this.getNewStarPosition();
        newStar.setPosition(this._starPos);
        (<Star>newStar.getComponent("Star")).game = this;
        this.starDuration = this.minStarDuration + Math.random() * (this.maxStarDuration - this.minStarDuration);
        this.timer = 0;
    }
    getNewStarPosition() {
        let randX = 0;
        let randY = this.groundY + Math.random() * (<Player>this.player.getComponent("Player")).jumpHeight + 50;
        randX = (Math.random() - 0.5) * this.node._uiProps.uiTransformComp!.width;
        Vec3.set(this._starPos, randX, randY, 0);
    }
    start() {
        this.groundY = this.ground!.position.y + this.ground!._uiProps.uiTransformComp!.height / 2;
        this.spawnNewStar();
    }
    update(dt: number) {
        if (this.timer > this.starDuration) {
            this.gameOver();
            return;
        }
        this.timer += dt;
    }
    gainScore() {
        this.score += 10;
        this.scoreDisplay.string = 'Score: ' + this.score;
        this.scoreAudioSource.play();
    }
    gameOver() {
        Tween.stopAllByTarget(this.player);
        director.loadScene('game');
    }
}